// 答题详情页面JavaScript

let quizData = null;

// 配置marked选项
if (typeof marked !== 'undefined') {
    marked.setOptions({
        breaks: true,
        gfm: true,
        sanitize: false
    });
}

// Markdown渲染辅助函数（支持数学公式）
function renderMarkdown(text) {
    if (!text) return '';
    if (typeof marked !== 'undefined') {
        return marked.parse(text);
    }
    return text;
}

// 渲染数学公式
function renderMath(element) {
    if (typeof window.renderMathInElement !== 'undefined' && typeof katex !== 'undefined') {
        try {
            window.renderMathInElement(element, {
                delimiters: [
                    {left: '$$', right: '$$', display: true},
                    {left: '$', right: '$', display: false},
                    {left: '\\[', right: '\\]', display: true},
                    {left: '\\(', right: '\\)', display: false}
                ],
                throwOnError: false
            });
        } catch (e) {
            console.warn('数学公式渲染失败:', e);
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('答题详情页面已加载');
    
    // 从URL参数或sessionStorage获取答题数据
    loadQuizData();
});

// 加载答题数据
function loadQuizData() {
    // 尝试从sessionStorage获取数据
    const storedData = sessionStorage.getItem('quizResult');
    
    if (storedData) {
        try {
            quizData = JSON.parse(storedData);
            displayQuizDetail(quizData);
        } catch (e) {
            console.error('解析答题数据失败:', e);
            showError('加载答题数据失败');
        }
    } else {
        showError('未找到答题数据');
    }
}

// 显示答题详情
function displayQuizDetail(data) {
    // 显示统计数据
    document.getElementById('totalCorrect').textContent = data.correctCount || 0;
    document.getElementById('totalWrong').textContent = data.wrongCount || 0;
    document.getElementById('totalScore').textContent = data.score || 0;
    
    // 显示用时
    const timeElapsed = data.timeElapsed || 0;
    const minutes = Math.floor(timeElapsed / 60);
    const seconds = timeElapsed % 60;
    const timeString = String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0');
    document.getElementById('timeElapsed').textContent = timeString;
    
    // 显示题目列表
    const questions = data.questions || [];
    const userAnswers = data.userAnswers || [];
    
    const questionsList = document.getElementById('questionsList');
    questionsList.innerHTML = '';
    
    questions.forEach((question, index) => {
        const questionElement = createQuestionElement(question, index, userAnswers[index]);
        questionsList.appendChild(questionElement);
    });
}

// 创建题目元素
function createQuestionElement(question, index, userAnswer) {
    const questionDiv = document.createElement('div');
    questionDiv.className = 'question-item';
    
    const isCorrect = userAnswer === question.correct;
    questionDiv.classList.add(isCorrect ? 'correct' : 'incorrect');
    
    // 题目序号和状态
    const statusIcon = isCorrect ? '✓' : '✗';
    const statusText = isCorrect ? '正确' : '错误';
    
    questionDiv.innerHTML = `
        <div class="question-header">
            <span class="question-number">第 ${index + 1} 题</span>
            <span class="question-status ${isCorrect ? 'status-correct' : 'status-wrong'}">
                ${statusIcon} ${statusText}
            </span>
        </div>
        
        <div class="question-content">
            <div class="question-title">${renderMarkdown(question.title)}</div>
            ${question.question_image ? `<img src="${question.question_image}" class="question-image" alt="题目配图">` : ''}
            
            <div class="question-options">
                ${question.options.map((option, optIndex) => {
                    const optionLetter = String.fromCharCode(65 + optIndex);
                    let optionClass = 'option';
                    
                    // 标记用户选择的答案
                    if (optIndex === userAnswer) {
                        optionClass += ' user-selected';
                    }
                    
                    // 标记正确答案
                    if (optIndex === question.correct) {
                        optionClass += ' correct-answer';
                    }
                    
                    // 标记错误答案（如果用户选错了）
                    if (!isCorrect && optIndex === userAnswer && optIndex !== question.correct) {
                        optionClass += ' wrong-answer';
                    }
                    
                    const imageKey = ['option_a_image', 'option_b_image', 'option_c_image', 'option_d_image'][optIndex];
                    const optionImage = question[imageKey] ? `<img src="${question[imageKey]}" class="option-image" alt="选项${optionLetter}配图">` : '';
                    
                    return `
                        <div class="${optionClass}">
                            <span class="option-label">${optionLetter}.</span>
                            <div class="option-content-inline">
                                <span class="option-text">${renderMarkdown(option || '(无选项)')}</span>
                                ${optionImage}
                            </div>
                        </div>
                    `;
                }).join('')}
            </div>
            
            ${question.explanation ? `
                <div class="question-explanation">
                    <div class="explanation-title">💡 答案解析：</div>
                    <div class="explanation-content">
                        ${renderMarkdown(question.explanation)}
                        ${question.explanation_image ? `<img src="${question.explanation_image}" class="explanation-image" alt="解析配图">` : ''}
                    </div>
                </div>
            ` : ''}
        </div>
    `;
    
    // 渲染题目和选项中的数学公式
    setTimeout(() => {
        renderMath(questionDiv);
    }, 0);
    
    return questionDiv;
}

// 显示错误信息
function showError(message) {
    const container = document.getElementById('questionsList');
    if (container) {
        container.innerHTML = `
            <div class="error-message">
                <p>${message}</p>
                <a href="/quiz" class="btn-back-quiz">返回答题</a>
            </div>
        `;
    }
}

